package com.han.hotelplat.comm.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

/***
 * 
 * @Title:
 * @Description 文件上传处理工具类
 * @author  han
 *   2016-5-16 下午03:04:37
 */
public class FileUtils {

	// 创建目录
	public static void createDir(String destDirName) {
		File dir = new File(destDirName);
		if (dir.exists()) {// 判断目录是否存在
			System.out.println("创建目录失败，目标目录已存在！");
		}
		if (!destDirName.endsWith(File.separator)) {// 结尾是否以"/"结束
			destDirName = destDirName + File.separator;
		}
		if (dir.mkdirs()) {// 创建目标目录
			System.out.println("创建目录成功！" + destDirName);
		} else {
			System.out.println("创建目录失败！");
		}
	}

	public static String saveFile(File file, String savePath, String filename, boolean isAutoName) {
		FileOutputStream fos = null;
		FileInputStream fis = null;
		try {
			// 建立文件输出流
			String savename = filename;
			if (isAutoName) {
				savename = getSaveName(file, filename);
			}
			System.out.println(savePath + File.separator + savename);
			if (!isFileExist(savePath))
				if(new File(savePath).mkdirs()){
					System.out.println("创建成功");
				} else {
					System.out.println("创建失败");
				}
			fos = new FileOutputStream(savePath + File.separator + savename);
			// 建立文件上传流
			fis = new FileInputStream(file);
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = fis.read(buffer)) > 0) {
				fos.write(buffer, 0, len);
			}
			return savename;
		} catch (Exception e) {
			System.out.println("文件上传失败");
			e.printStackTrace();
			return null;
		} finally {
			close(fos, fis);
		}
	}

	private static String getSaveName(File file, String filename) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		Random rd = new Random();
		// 获得后缀
		String typename = filename.substring(filename.lastIndexOf(".") + 1);
		// 随机产生名字
		String savename = sdf.format(new Date()) + "_" + rd.nextInt(999999) + "." + typename;
		return savename;
	}

	private static void close(FileOutputStream fos, FileInputStream fis) {
		if (fis != null) {
			try {
				fis.close();
			} catch (IOException e) {
				System.out.println("FileInputStream关闭失败");
				e.printStackTrace();
			}
		}
		if (fos != null) {
			try {
				fos.close();
			} catch (IOException e) {
				System.out.println("FileOutputStream关闭失败");
				e.printStackTrace();
			}
		}
	}

	/**
	 * 读取文件每一行，返回set
	 */
	@SuppressWarnings("resource")
	public static Set<String> readFile(File file) {
		Set<String> set = new HashSet<String>();
		try {
			BufferedReader reader = new BufferedReader(new FileReader(file));
			String str = null;
			while ((str = reader.readLine()) != null) {
				if (!ValidateUtil.str_isEmpty(str))
					set.add(str);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return set;
	}

	/** 
	 * 删除单个文件 
	 * @param   sPath    被删除文件的文件名 
	 * @return 单个文件删除成功返回true，否则返回false 
	 */
	public static boolean deleteFile(String sPath) {
		boolean flag = false;
		try {
			File file = new File(sPath);
			// 路径为文件且不为空则进行删除
			if (file.isFile() && file.exists()) {
				file.delete();
				flag = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}

	/**
	 * 下载文件
	 * @param urlString 请求路径
	 * @param filename 文件名
	 * @param savePath 保存路径
	 * @throws IOException
	 */
	public static void download(String urlString, String filename, String savePath) throws IOException {
	    // 构造URL
	    URL url = new URL(urlString);
	    // 打开连接
	    URLConnection con = url.openConnection();
	    //设置请求超时为5s
	    con.setConnectTimeout(5*1000);
	    // 输入流
	    InputStream is = con.getInputStream();
	
	    // 1K的数据缓冲
	    byte[] bs = new byte[1024];
	    // 读取到的数据长度
	    int len;
	    // 输出的文件流
	   File sf=new File(savePath);
	   if(!sf.exists()){
		   sf.mkdirs();
	   }
	   OutputStream os = new FileOutputStream(sf.getPath()+"\\"+filename);
	    // 开始读取
	    while ((len = is.read(bs)) != -1) {
	      os.write(bs, 0, len);
	    }
	    // 完毕，关闭所有链接
	    os.close();
	    is.close();
	}

	/**
	 * 判断文件是否存在
	 */
	public static boolean isFileExist(String filePath){
		if(StringUtils.isNotEmpty(filePath)){
			File file = new File(filePath);
			return file != null && file.isFile() && file.exists();
		}
		return false;
	}
}
